package zijie;

import java.util.HashMap;
import java.util.Stack;

public class IsValid_20_30 {
    public boolean isValid(String s) {
        if(s.length() %2 == 1){
            return false;
        }
        Stack<Character> stack = new Stack<>();
        HashMap<Character,Character> template = new HashMap<>();
        template.put('}','{');
        template.put(')','(');
        template.put(']','[');

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(template.containsKey(c)){
                if(stack.empty() || template.get(c) != stack.peek()){
                    return false;
                }
                stack.pop();
            }else{
                stack.push(c);
            }
        }
        return stack.isEmpty();
    }
}
